package com.itmei.sms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.itmei.sms.config.SmsSupplierConfig;
import com.itmei.sms.entity.*;
import com.itmei.sms.enums.SmsResponseEnum;
import com.itmei.sms.enums.SmsSceneEnum;
import com.itmei.sms.service.SmsInterface;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.CompletableFuture;


/**
 * @Author itmei
 * @Date 2023/1/31 11:25
 * @description: 阿里云短信实现类
 * @Title: SmsServiecImpl
 * @Package com.itmei.sms.service.impl
 */
public class SmsAliyunServiceImpl implements SmsInterface {

    private final static Logger log= LoggerFactory.getLogger(SmsAliyunServiceImpl.class);
    /**
     * 唯一标识和短信供应商枚举一致
     */
    public final static String Code="aliyun_sms";

    @Override
    public SmsResult sendSms(SmsConfig config, String mobile, SmsTemplateConfig smsTemplateConfig) {
        SmsTemplateResult departmentTemplate = getDepartmentTemplateParam(smsTemplateConfig);
        log.info(">>> 开始发送阿里云短信，手机号是：" + mobile + ",模板号是：" + departmentTemplate.getTemplateCode() + ",参数:" + smsTemplateConfig.getTemplateParam());

        SmsResult result = new SmsResult();
        //发送逻辑代码
        // 配置凭证认证信息，包括ak、secret、token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(config.getAccessKeyId())
                .accessKeySecret(config.getAccessKeySecret())
                //.securityToken("<your-token>") // 也可以设置token
                .build());

        // 配置客户端
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        //获取签名名称
        String signName = config.getSignName();

        // API请求参数设置
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .templateParam(departmentTemplate.getTemplateParam())
                .templateCode(departmentTemplate.getTemplateCode())
                .phoneNumbers(mobile)
                .signName(signName)
                .build();
        // 异步获取API请求的返回值
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 同步获取API请求的返回值
        SendSmsResponse resp = null;
        JSONObject json = null;
        try {
            resp = response.get();
            json = JSONUtil.parseObj(resp).getJSONObject("body");
            result.setCode(json.getStr("code"));
            result.setBizId(json.getStr("bizId"));
            result.setRequestId(json.getStr("requestId"));
            result.setResponse(json.toString());
            log.info(">>> 阿里云短信，响应信息：{}",json.toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(SmsResponseEnum.ERROR.getCode());
            result.setErrorMsg(e.getMessage());
        }finally {
            client.close();
        }
        if (!SmsResponseEnum.OK.getCode().equals(result.getCode())){
            if (ObjectUtil.isNotEmpty(json)){
                result.setErrorMsg(json.getStr("message"));
            }
            log.error(">>> 阿里云短信发送异常！code = " + result.getCode()+ ",errorMsg = " + result.getErrorMsg() + ",message = " + result.getResponse());
        }
        SysSms sms = new SysSms();
        sms.setPhoneNumbers(mobile);
        //验证码
        sms.setValidateCode(departmentTemplate.getValidateCode());
        sms.setTemplateCode(departmentTemplate.getTemplateCode());
        sms.setTemplateParam(departmentTemplate.getTemplateParam());
        sms.setBizId(result.getBizId());
        sms.setErrorMsg(result.getErrorMsg());
        result.setSysSms(sms);
        return result;
    }

    @Override
    public SmsTemplateResult getDepartmentTemplateParam(SmsTemplateConfig smsTemplateConfig) {
        SmsTemplateResult smsTemplateResult = new SmsTemplateResult();
        Integer sceneCode = smsTemplateConfig.getSceneEnum();
        //获取对应的模板信息
        String templateCode = SmsSupplierConfig.getSmsSceneCode(Code,SmsSceneEnum.getSmsSceneEnum(sceneCode).getSceneCode());
        smsTemplateResult.setTemplateCode(templateCode);
        //验证码的单独处理
        if (SmsSceneEnum.VERIFICATION_CODE_SMS.getCode().equals(sceneCode)) {
            //短信验证码
            Map<String, Object> templateParam = smsTemplateConfig.getTemplateParam();
            //设置验证码到参数中
            String validateCode = RandomUtil.randomNumbers(6);
            templateParam.put("code", validateCode);
            smsTemplateResult.setValidateCode(validateCode);
        }
        smsTemplateResult.setTemplateParam(JSONUtil.toJsonStr(smsTemplateConfig.getTemplateParam()));
        return smsTemplateResult;
    }

}
